package com.voxel.sense.infomsg.view.dropmenu;


import android.content.Context;
import android.content.res.TypedArray;
import android.support.annotation.NonNull;
import android.text.TextUtils;
import android.util.AttributeSet;
import android.util.DisplayMetrics;
import android.util.TypedValue;
import android.view.Gravity;
import android.view.View;
import android.view.ViewGroup;
import android.view.animation.AnimationUtils;
import android.widget.FrameLayout;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.example.com.common.utils.ScreenUtils;
import com.voxel.sense.infomsg.R;

import java.util.List;

/**
 * Created by ChenYiYao on 2018/6/27.
 */
public class DropDownMenu extends LinearLayout {


    //顶部菜单布局
    private LinearLayout mTabMenuView;
    //底部容器 包含popMenuViews,maskView
    private FrameLayout mContainerView;
    //弹出菜单的父布局
    private FrameLayout mPopMenuView;
    //半透明遮罩
    private View mMaskView;
    //mTabMenuView当中的选中项位置
    private int mCurrentTapPosition = -1;
    //分割线颜色
    private int mDividerColor = 0xffcccccc;
    //tab选中的颜色
    private int mTextSelecteColor = 0xff890c85;
    //tab未选中颜色
    private int mTextUnselectedColor = 0xff111111;
    //遮罩颜色
    private int mMaskColor = 0x88888888;
    //tab字体大小
    private int mMenuTextSize = 14;

    //tab选中图标
    private int mMenuSelectedIcon;
    //tab未选中图标
    private int mMenuUnselectedIcon;

    //menu占高比例
    private float mMenuHeighPercent = 0.5f;
    //分割线颜色
    private float mDividerHeight;
    //icon的方向
    private static int mIconOrientation = Orientation.right;
    private Orientation mOrientation;


    public DropDownMenu(Context context) {
        this(context, null);
    }

    public DropDownMenu(Context context, AttributeSet attrs) {
        this(context, attrs, 0);
    }

    public DropDownMenu(Context context, AttributeSet attrs, int defStyleAttr) {
        super(context, attrs, defStyleAttr);
        //设置水平方向排列
        setOrientation(VERTICAL);

        //添加自定义属性
        int menuBackgroundColor = 0xffffffff;
        int underlineColor = 0xffcccccc;
        TypedArray a = context.obtainStyledAttributes(attrs, R.styleable.DropDownMenu);
        underlineColor = a.getColor(R.styleable.DropDownMenu_ddunderlineColor, underlineColor);
        mDividerColor = a.getColor(R.styleable.DropDownMenu_dddividerColor, mDividerColor);
        mTextSelecteColor = a.getColor(R.styleable.DropDownMenu_ddtextSelectedColor, mTextSelecteColor);
        mTextUnselectedColor = a.getColor(R.styleable.DropDownMenu_ddtextUnselectedColor, mTextUnselectedColor);
        menuBackgroundColor = a.getColor(R.styleable.DropDownMenu_ddmenuBackgroundColor, menuBackgroundColor);
        mMaskColor = a.getColor(R.styleable.DropDownMenu_ddmaskColor, mMaskColor);
        mMenuTextSize = a.getDimensionPixelSize(R.styleable.DropDownMenu_ddmenuTextSize, mMenuTextSize);
        mMenuSelectedIcon = a.getResourceId(R.styleable.DropDownMenu_ddmenuSelectedIcon, mMenuSelectedIcon);
        mMenuUnselectedIcon = a.getResourceId(R.styleable.DropDownMenu_ddmenuUnselectedIcon, mMenuSelectedIcon);
        mMenuHeighPercent = a.getFloat(R.styleable.DropDownMenu_ddmenuHeightPercent, mMenuHeighPercent);
        a.recycle();
        //初始化位置参数
        mOrientation = new Orientation();
        mOrientation.init(mIconOrientation, getResources().getDrawable(mMenuSelectedIcon), getResources().getDrawable(mMenuUnselectedIcon));


        //初始化tabMenuView并添加到tabMenuView
        mTabMenuView = new LinearLayout(context);
        LayoutParams params = new LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.WRAP_CONTENT);
        mTabMenuView.setOrientation(HORIZONTAL);
        mTabMenuView.setBackgroundColor(menuBackgroundColor);
        mTabMenuView.setLayoutParams(params);
        addView(mTabMenuView, 0);

        //为tabMenuView添加分割线
        View underLine = new View(context);
        underLine.setBackgroundColor(underlineColor);
        underLine.setLayoutParams(new LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, dpToPx(1.0f)));
        addView(underLine, 1);

        //初始化containerView并将其添加到DropDownMenu中
        mContainerView = new FrameLayout(context);
        mContainerView.setLayoutParams(new FrameLayout.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.MATCH_PARENT));
        addView(mContainerView, 2);
    }


    public void setDropDownMenu(@NonNull List<String> tabTexts, @NonNull List<View> popupViews, @NonNull View contentView) {
        if (tabTexts.size() != popupViews.size()) {
            throw new IllegalArgumentException("params not match, tabTexts.size() should be equal popupViews.size()");
        }
        for (int i = 0; i < tabTexts.size(); i++) {
            addTab(tabTexts, i);
        }
        mContainerView.addView(contentView, 0);

        mMaskView = new View(getContext());
        mMaskView.setLayoutParams(new FrameLayout.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.MATCH_PARENT));
        mMaskView.setBackgroundColor(mMaskColor);
        mMaskView.setOnClickListener(new OnClickListener() {
            @Override
            public void onClick(View v) {
                closeMenu();
            }
        });
        mContainerView.addView(mMaskView, 1);
        mMaskView.setVisibility(GONE);

        if (mContainerView.getChildAt(2) != null) {
            mContainerView.removeViewAt(2);
        }

        mPopMenuView = new FrameLayout(getContext());
        mPopMenuView.setLayoutParams(new FrameLayout.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, (int) (ScreenUtils.getScreenHeight() * mMenuHeighPercent)));
        mPopMenuView.setVisibility(GONE);
        mContainerView.addView(mPopMenuView, 2);

        for (int i = 0; i < popupViews.size(); i++) {
            popupViews.get(i).setLayoutParams(new ViewGroup.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.WRAP_CONTENT));
            mPopMenuView.addView(popupViews.get(i), i);
        }
    }

    public void closeMenu() {
        if (mCurrentTapPosition != -1) {
            TextView tabTextView = getTabTextView(mTabMenuView.getChildAt(mCurrentTapPosition));
            setTabTextStyle(tabTextView, mTextUnselectedColor, true);
            mPopMenuView.setVisibility(GONE);
            mPopMenuView.setAnimation(AnimationUtils.loadAnimation(getContext(), R.anim.dd_menu_out));
            mMaskView.setVisibility(GONE);
            mMaskView.setAnimation(AnimationUtils.loadAnimation(getContext(), R.anim.dd_mask_out));
            mCurrentTapPosition = -1;

        }
    }

    private void addTab(List<String> tabTexts, int i) {
        View tab = inflate(getContext(), R.layout.item_drop_menu_tab, null);
        tab.setLayoutParams(new LayoutParams(0, ViewGroup.LayoutParams.WRAP_CONTENT, 1.0f));
        TextView tv_tab = tab.findViewById(R.id.tv_tab);
        tv_tab.setSingleLine();
        tv_tab.setEllipsize(TextUtils.TruncateAt.END);
        tv_tab.setGravity(Gravity.CENTER);
        tv_tab.setTextSize(TypedValue.COMPLEX_UNIT_PX, mMenuTextSize);
        setTabTextStyle(tv_tab, mTextUnselectedColor, true);
        tv_tab.setText(tabTexts.get(i));
        tv_tab.setPadding(dpToPx(5), dpToPx(12), dpToPx(5), dpToPx(12));
        //添加点击事件
        tab.setOnClickListener(new OnClickListener() {
            @Override
            public void onClick(View v) {
                switchMenu(v);
            }
        });
        mTabMenuView.addView(tab);
        //添加分割线
        if (i < tabTexts.size() - 1) {
//            View view = new View(getContext());
//            view.setLayoutParams(new LayoutParams(dpToPx(0.5f), ViewGroup.LayoutParams.MATCH_PARENT));
//            view.setBackgroundColor(mDividerColor);
            mTabMenuView.addView(getDividerView());
        }
    }

    /**
     * 插入自定义的view，如果包含R.id.tv_tab就当做普通的tabView做统一处理
     *
     * @param tab
     * @param index
     */
    public void addTab(View tab, int index) {
        if (index == (mTabMenuView.getChildCount() + 1) / 2) {
            addTabEnd(tab);
            return;
        }
        mTabMenuView.addView(tab, index * 2);
        //添加分割线
        mTabMenuView.addView(getDividerView(), index * 2 + 1);
    }

    private View getDividerView() {
        //            View view = new View(getContext());
//            view.setLayoutParams(new LayoutParams(dpToPx(0.5f), ViewGroup.LayoutParams.MATCH_PARENT));
//            view.setBackgroundColor(mDividerColor);
        View view = new View(getContext());
        int height = mDividerHeight > 0 ? dpToPx(mDividerColor) : -1;
        LayoutParams params = new LayoutParams(dpToPx(0.5f), height);
        params.gravity = Gravity.CENTER_VERTICAL;
        view.setLayoutParams(params);
        view.setBackgroundColor(mDividerColor);
        return view;
    }

    private TextView getTabTextView(View tabView) {
        TextView tv = tabView.findViewById(R.id.tv_tab);
        return tv;
    }

    private void addTabEnd(View tab) {
        mTabMenuView.addView(getDividerView(), mTabMenuView.getChildCount());
        //添加分割线
        mTabMenuView.addView(tab, mTabMenuView.getChildCount());
    }


    /**
     * 改变tab文字
     *
     * @param text
     */
    public void setTabText(String text) {
        if (mCurrentTapPosition != -1) {
            getTabTextView(mTabMenuView.getChildAt(mCurrentTapPosition)).setText(text);
        }
    }

    public void setTextDrawables(TextView textview, boolean close) {
        textview.setCompoundDrawablesWithIntrinsicBounds(mOrientation.getLeft(close), mOrientation.getTop(close),
                mOrientation.getRight(close), mOrientation.getBottom(close));
    }


    /**
     * 切换菜单
     *
     * @param tab
     */
    private void switchMenu(View tab) {
        for (int i = 0; i < mTabMenuView.getChildCount(); i = i + 2) {
            if (tab == mTabMenuView.getChildAt(i)) {
                //选择相同菜单item，则收起列表k
                if (mCurrentTapPosition == i) {
                    closeMenu();
                } else {
                    if (mCurrentTapPosition == -1) {
                        mPopMenuView.setVisibility(View.VISIBLE);
                        mPopMenuView.setAnimation(AnimationUtils.loadAnimation(getContext(), R.anim.dd_menu_in));
                        mMaskView.setVisibility(VISIBLE);
                        mMaskView.setAnimation(AnimationUtils.loadAnimation(getContext(), R.anim.dd_mask_in));
                        mPopMenuView.getChildAt(i / 2).setVisibility(VISIBLE);
                    } else {
                        mPopMenuView.getChildAt(i / 2).setVisibility(VISIBLE);
                    }
                    mCurrentTapPosition = i;
                    TextView tabTextView = getTabTextView(mTabMenuView.getChildAt(i));
                    setTabTextStyle(tabTextView, mTextSelecteColor, false);
                }
            } else {
                mPopMenuView.getChildAt(i / 2).setVisibility(GONE);
                TextView tabTextView = getTabTextView(mTabMenuView.getChildAt(i));
                setTabTextStyle(tabTextView, mTextUnselectedColor, true);
            }
        }

    }

    private void setTabTextStyle(TextView tabTextView, int Color, boolean flag) {
        tabTextView.setTextColor(Color);
        setTextDrawables(tabTextView, flag);
    }


    public int dpToPx(float value) {
        DisplayMetrics dm = getResources().getDisplayMetrics();
        return (int) (TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_DIP, value, dm) + 0.5);
    }


}
